﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using KPIS.GERP.GIMS.BLL;
using KPIS.GERP.GIMS.IBLL;
using KPIS.GERP.GIMS.MODEL;
using System.Data;

namespace KPIS.GERP.GIMS.APP.APP_UI.Form
{
    public partial class ICM_Master_Committee_Mapping : System.Web.UI.Page
    {
        Common.Main cn = new Common.Main();
        CommandControl cmdFac = new CommandControl();
        IBLLMasterPurchaseMapping bllPurchase = new MasterPurchaseMappingBLL();
        IBLLMasterCommitteeMapping bllCommittee = new MasterCommitteeMappingBLL();
        IBLLMasterCommitteeFunction bllFunction = new MasterCommitteeFunctionBLL();
        IBLLMasterCommitteePosition bllPosition = new MasterCommitteePositionBLL();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadDataGridMethod();
                LoadCommitteeFunction();
                LoadCommitteePosition();
                panelCommand.Visible = false;
                panelData.Visible = false;
            }

            LoadCommitteePositionDetail();
        }

        public void SetHeader(string header_type, string header_method)
        {
            lblHeaderList.Text = "คณะกรรมการที่เกี่ยวข้องกับ [การ" + header_type + "ด้วย" + header_method + "]";
        }

        public void LoadDataGridMethod()
        {
            IList<MasterPurchaseMappingInfo> info = bllPurchase.GetMasterPurchaseMapping();
            GridMethod.DataSource = info;
            GridGroupByExpression ge = new GridGroupByExpression(GridMethod.Columns[0]);
            GridMethod.MasterTableView.GroupByExpressions.Add(ge);
            GridGroupByExpression ge1 = new GridGroupByExpression(GridMethod.Columns[1]);
            GridMethod.MasterTableView.GroupByExpressions.Add(ge1);
            GridMethod.DataBind();
        }

        public void LoadDataGridCommittee(int map_seq)
        {
            IList<MasterCommitteeMappingInfo> info = bllCommittee.GetMasterCommitteeMappingWithMethod(map_seq);
            Grid.DataSource = info;
            GridGroupByExpression ge = new GridGroupByExpression(Grid.Columns[1]);
            Grid.MasterTableView.GroupByExpressions.Add(ge);
            GridGroupByExpression ge1 = new GridGroupByExpression(Grid.Columns[2]);
            Grid.MasterTableView.GroupByExpressions.Add(ge1);
            Grid.DataBind();
            cmdFac.GridCommand(panelList, panelGrid, panelCommand);
        }

        public void LoadCommitteeFunction()
        {
            IList<MasterCommitteeFunctionInfo> info = bllFunction.GetMasterCommitteeFunction();
            cbFunction.DataSource = info;
            cbFunction.DataBind();
        }

        public void LoadCommitteePosition()
        {
            IList<MasterCommitteePositionInfo> info = bllPosition.GetMasterCommitteePosition();
            cblPosition.DataSource = info;
            cblPosition.DataBind();
        }

        public void LoadCommitteePositionDetail()
        {
            for (int i = 0; i < cblPosition.Items.Count; i++)
            {
                TableRow tr = new TableRow();
                TableCell td = new TableCell();
                RadNumericTextBox txt = new RadNumericTextBox();
                txt.ID = "txt_" + cblPosition.Items[i].Value;
                txt.Width = Unit.Pixel(50);
                //txt.CssClass = "RadNumericTextBox";
                txt.Skin = "Outlook";
                txt.NumberFormat.DecimalDigits = 0;
                Label lbl = new Label();
                lbl.Text = " คน";
                td.VerticalAlign = VerticalAlign.Top;
                td.Controls.Add(txt);
                td.Controls.Add(lbl);
                tr.Cells.Add(td);
                tableNumPosition.Rows.Add(tr);
            }
        }

        protected void AddNew_Click(object sender, EventArgs e)
        {
            cmdFac.AddNewCommand(panelList, panelGrid, panelCommand);
            SetAmountCondition();
            ResetCommitteePosition();
        }

        protected void SetAmountCondition()
        {
            MasterPurchaseMappingInfo info = bllPurchase.GetMasterPurchaseMapping(Convert.ToInt32(hdMethod.Value));
            txtLessMinAmount.Text = info.Min_amount.ToString();
            txtBetweenMinAmount.Text = info.Min_amount.ToString();
            txtBetweenMaxAmount.Text = info.Max_amount.ToString();
            txtMoreMaxAmount.Text = info.Max_amount.ToString();
            rdbAmountNone.Checked = false;
            rdbAmountLess.Checked = false;
            rdbAmountBetween.Checked = false;
            rdbAmountMore.Checked = false;

            if (info.Amount_type == "")
            {
                rdbAmountNone.Checked = true;
                rdbAmountNone_CheckedChanged(null, null);
            }
            else if (info.Amount_type == "<")
            {
                rdbAmountLess.Checked = true;
                rdbAmountLess_CheckedChanged(null, null);
            }
            else if (info.Amount_type == "-")
            {
                rdbAmountBetween.Checked = true;
                rdbAmountBetween_CheckedChanged(null, null);
            }
            else if (info.Amount_type == ">")
            {
                rdbAmountMore.Checked = true;
                rdbAmountMore_CheckedChanged(null, null);
            }
        }

        protected void Delete_Click(object sender, EventArgs e)
        {
            IList<MasterCommitteeMappingInfo> infoList = new List<MasterCommitteeMappingInfo>();
            if (panelGrid.Visible)
            {
                foreach (GridDataItem data in Grid.MasterTableView.GetSelectedItems())
                {
                    MasterCommitteeMappingInfo info = new MasterCommitteeMappingInfo();
                    RecordInfo infoRecord = new RecordInfo();
                    info.Seq = Convert.ToInt32(data.OwnerTableView.DataKeyValues[data.ItemIndex]["Seq"]);
                    infoRecord.Updated_by = Int32.Parse(Session["EmpSeq"].ToString());
                    infoRecord.Updated_when = DateTime.Now;
                    info.InfoRecord = infoRecord;
                    infoList.Add(info);
                }
            }
            else
            {
                MasterCommitteeMappingInfo info = new MasterCommitteeMappingInfo();
                RecordInfo infoRecord = new RecordInfo();
                info.Seq = Convert.ToInt32(hdSeq.Value);
                infoRecord.Updated_by = Int32.Parse(Session["EmpSeq"].ToString());
                infoRecord.Updated_when = DateTime.Now;
                info.InfoRecord = infoRecord;
                infoList.Add(info);
            }

            if (infoList.Count == 0)
            {
                RadManager1.Alert(SystemInfo._DeleteNull);
                return;
            }

            try
            {
                bllCommittee.DeleteFromDB(infoList);
            }
            catch
            {
                RadManager1.Alert(SystemInfo._DeleteError);
                return;
            }

            LoadDataGridCommittee(Convert.ToInt32(hdMethod.Value));
        }

        protected void AddNewSave_Click(object sender, EventArgs e)
        {
            IList<MasterCommitteeMappingInfo> infoList = new List<MasterCommitteeMappingInfo>();
            bool bOK = false;

            for (int i = 0; i < cblPosition.Items.Count; i++)
            {
                if (cblPosition.Items[i].Selected)
                {
                    foreach (Control child in tableNumPosition.Rows[i].Cells[0].Controls)
                    {
                        if (child.GetType().ToString().Equals("Telerik.Web.UI.RadNumericTextBox")
                              && child.ID.IndexOf("txt_") == 0)
                        {
                            RadNumericTextBox textbox = (RadNumericTextBox)child;
                            if (textbox.Text.Length == 0)
                            {
                                RadManager1.Alert("กรุณาระบุจำนวนตำแหน่งให้ครบถ้วน");
                                return;
                            }
                            else
                            {
                                for (int j = 0; j < Convert.ToInt32(textbox.Value); j++)
                                {
                                    MasterCommitteeMappingInfo info = new MasterCommitteeMappingInfo();
                                    MasterCommitteeFunctionInfo infoFunction = new MasterCommitteeFunctionInfo();
                                    MasterCommitteePositionInfo infoPosition = new MasterCommitteePositionInfo();
                                    MasterPurchaseMappingInfo infoPurchase = new MasterPurchaseMappingInfo();
                                    RecordInfo infoRecord = new RecordInfo();

                                    if (rdbAmountNone.Checked)
                                    {
                                        info.Amount_type = "";
                                    }
                                    else if (rdbAmountLess.Checked)
                                    {
                                        info.Amount_type = "<";
                                        info.Min_amount = (txtLessMinAmount.Text.Length == 0 ? null : (Nullable<double>)Convert.ToDouble(txtLessMinAmount.Text));
                                    }
                                    else if (rdbAmountBetween.Checked)
                                    {
                                        info.Amount_type = "-";
                                        info.Min_amount = (txtBetweenMinAmount.Text.Length == 0 ? null : (Nullable<double>)Convert.ToDouble(txtBetweenMinAmount.Text));
                                        info.Max_amount = (txtBetweenMaxAmount.Text.Length == 0 ? null : (Nullable<double>)Convert.ToDouble(txtBetweenMaxAmount.Text));
                                    }
                                    else if (rdbAmountMore.Checked)
                                    {
                                        info.Amount_type = ">";
                                        info.Max_amount = (txtMoreMaxAmount.Text.Length == 0 ? null : (Nullable<double>)Convert.ToDouble(txtMoreMaxAmount.Text));
                                    }

                                    if (bOK == false)
                                    {
                                        try
                                        {
                                            bllCommittee.CheckData(info);
                                            bOK = true;
                                        }
                                        catch (Exception ex)
                                        {
                                            RadManager1.Alert(ex.Message);
                                            return;
                                        }
                                    }

                                    infoPurchase.Seq = Convert.ToInt32(hdMethod.Value);
                                    infoFunction.Seq = Convert.ToInt32(cbFunction.SelectedValue);
                                    infoPosition.Seq = Convert.ToInt32(cblPosition.Items[i].Value);
                                    infoRecord.Created_by = cn.UserID;
                                    infoRecord.Created_when = DateTime.Now;

                                    info.InfoPurchaseMapping = infoPurchase;
                                    info.InfoFunction = infoFunction;
                                    info.InfoPosition = infoPosition;
                                    info.InfoRecord = infoRecord;

                                    info.NUMBER_COM_FUNC = bllCommittee.GetMaxNumberComFunction(Convert.ToInt32(infoPurchase.Seq));
                                    infoList.Add(info);
                                }
                            }
                        }
                    }    
                }
            }

            try
            {
              //  bllCommittee.GetMaxNumberComFunction();
                bllCommittee.Insert(infoList);
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
                return;
            }
            LoadDataGridCommittee(Convert.ToInt32(hdMethod.Value));
        }

        protected void ShowGrid_Click(object sender, EventArgs e)
        {
            LoadDataGridCommittee(Convert.ToInt32(hdMethod.Value));
        }

        protected void Grid_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadDataGridCommittee(Convert.ToInt32(hdMethod.Value));
        }

        protected void RadManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            if (e.Argument == "Method")
            {
                LoadDataGridCommittee(Convert.ToInt32(hdMethod.Value));
                MasterPurchaseMappingInfo info = bllPurchase.GetMasterPurchaseMapping(Convert.ToInt32(hdMethod.Value));
                SetHeader(info.InfoMethod.InfoType.Name, info.InfoMethod.Name);
                panelBlank.Visible = false;
                panelCommand.Visible = true;
                panelData.Visible = true;
            }
        }

        protected void rdbAmountNone_CheckedChanged(object sender, EventArgs e)
        {
            DisableRadNumericTextBox(txtLessMinAmount);
            DisableRadNumericTextBox(txtBetweenMinAmount);
            DisableRadNumericTextBox(txtBetweenMaxAmount);
            DisableRadNumericTextBox(txtMoreMaxAmount);
        }

        protected void rdbAmountLess_CheckedChanged(object sender, EventArgs e)
        {
            EnableRadNumericTextBox(txtLessMinAmount);
            DisableRadNumericTextBox(txtBetweenMinAmount);
            DisableRadNumericTextBox(txtBetweenMaxAmount);
            DisableRadNumericTextBox(txtMoreMaxAmount);
            txtLessMinAmount.Focus();
        }

        protected void rdbAmountBetween_CheckedChanged(object sender, EventArgs e)
        {
            DisableRadNumericTextBox(txtLessMinAmount);
            EnableRadNumericTextBox(txtBetweenMinAmount);
            EnableRadNumericTextBox(txtBetweenMaxAmount);
            DisableRadNumericTextBox(txtMoreMaxAmount);
            txtBetweenMinAmount.Focus();
        }

        protected void rdbAmountMore_CheckedChanged(object sender, EventArgs e)
        {
            DisableRadNumericTextBox(txtLessMinAmount);
            DisableRadNumericTextBox(txtBetweenMinAmount);
            DisableRadNumericTextBox(txtBetweenMaxAmount);
            EnableRadNumericTextBox(txtMoreMaxAmount);
            txtMoreMaxAmount.Focus();
        }

        private void DisableRadNumericTextBox(RadNumericTextBox txt)
        {
            txt.Text = "";
            txt.Enabled = false;
        }

        private void EnableRadNumericTextBox(RadNumericTextBox txt)
        {
            txt.Enabled = true;
        }

        private void ResetCommitteePosition()
        {
            cblPosition.ClearSelection();
            for (int i = 0; i < cblPosition.Items.Count; i++)
            {
                foreach (Control child in tableNumPosition.Rows[i].Cells[0].Controls)
                {
                    if (child.GetType().ToString().Equals("Telerik.Web.UI.RadNumericTextBox")
                          && child.ID.IndexOf("txt_") == 0)
                    {
                        RadNumericTextBox textbox = (RadNumericTextBox)child;
                        textbox.Text = "";
                    }
                }
            }
        }

        protected void OnAjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            RadAjaxPanel1.Controls.Add(Page.LoadControl("../UserControl/Personal_Data.ascx"));
        }

        protected void clearFilter_Click(object sender, EventArgs e)
        {
            foreach (GridColumn column in Grid.MasterTableView.Columns)
            {
                column.CurrentFilterFunction = GridKnownFunction.NoFilter;
                column.CurrentFilterValue = string.Empty;
            }
            Grid.MasterTableView.FilterExpression = string.Empty;
            LoadDataGridCommittee(Convert.ToInt32(hdMethod.Value));
        }
    }
}
